package com.yjd.back.commodit;

import java.util.*;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.enums.CommoditCategoryEnum;
import com.yjd.comm.enums.ReferenceTypeEnum;
import com.yjd.comm.fs.util.FileUtil;
import com.yjd.comm.merchant.model.MerchantProjectVerifyModel;
import com.yjd.comm.merchant.service.IMerchantProjectVerifyService;
import com.yjd.comm.project.model.PrjCategoryModel;
import com.yjd.comm.project.model.ProjectModel;
import com.yjd.comm.project.service.IPrjCategoryService;
import com.yjd.comm.project.service.IProjectService;
import com.yjd.comm.system.dto.AdminDataWrap;
import com.yjd.comm.system.model.AdminModel;
import com.yjd.comm.system.util.AdminDataUtil;
import com.yjd.comm.util.FrameUtil;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.yjd.comm.util.StringUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.yjd.comm.util.*;
import javax.annotation.Resource;
import com.yjd.comm.base.model.PagerHtmlModel;

/**
 * 后台商品信息管理
 * Created by weili.
 */
@Controller(" com.yjd.back.commodit.CommoditControl")
@Scope("prototype")
@RequestMapping("/commodit")
public class CommoditControl extends BaseControl{

    /**
     * 商品列表
     * @return
     * @throws Exception
     */
    @RequestMapping("/list")
    public String list() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getPageParameterMap(request);
        PagerHtmlModel pager = PagerUtil.getPagerHtmlModel(merchantProjectVerifyService.getPageModel(paramMap, DbWREnums.READ),paramMap, ServletUtil.getUrl("/commodit/list"));
        List<MerchantProjectVerifyModel> list = pager.getPagerModel().getDataList();
        List<PrjCategoryModel> categorys = prjCategoryService.getModelList(FrameUtil.newHashMap("is_used",1),DbWREnums.READ);
        for (MerchantProjectVerifyModel model : list){
            model.getStrMap().put("submit_time", DateUtil.timestampToDateString1(model.getAdd_time(), "yyyy-MM-dd"));
            for (PrjCategoryModel pcm : categorys){
                if (model.getCategory_id() == pcm.getId().longValue()){
                    model.getStrMap().put("category_name",pcm.getName());
                    break;
                }
            }
        }
        pager.getPagerModel().setDataList(list);
        this.request.setAttribute("categorys", categorys);
        this.request.setAttribute("paramMap", paramMap);
        this.request.setAttribute("pager", pager);
        return "commodit.list";
    }

    /***
     * 商品审核
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/check/{id}")
    public String check(@PathVariable("id") Long id) throws Exception {
        if(null == id){
            FrameUtil.throwBaseException1("商品ID获取失败！");
        }
        MerchantProjectVerifyModel model = merchantProjectVerifyService.getModelById(id, DbWREnums.READ);
        if (model == null){
            FrameUtil.throwBaseException1("商品信息不存在！");
        }
        PrjCategoryModel categoryModel = prjCategoryService.getModelById(model.getCategory_id(), DbWREnums.READ);
        if (categoryModel == null){
            FrameUtil.throwBaseException1("该分类不存在！");
        }
        model.getStrMap().put("category", categoryModel.getName());

        if (StringUtil.isNotEmpty(model.getProject_pic())){
            model.getStrMap().put("picUrl", ServletUtil.getFileUrl(model.getProject_pic()));
        }
        request.setAttribute("commodit", model);
        return "commodit.check";
    }

    /***
     * 商品修改
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id) throws Exception {
        if(null == id){
            FrameUtil.throwBaseException1("商品ID获取失败！");
        }
        MerchantProjectVerifyModel model = merchantProjectVerifyService.getModelById(id, DbWREnums.READ);
        if (model == null){
            FrameUtil.throwBaseException1("商品信息不存在！");
        }
        PrjCategoryModel categoryModel = prjCategoryService.getModelById(model.getCategory_id(), DbWREnums.READ);
        if (categoryModel == null){
            FrameUtil.throwBaseException1("该分类不存在！");
        }
        model.getStrMap().put("category", categoryModel.getName());

        if (StringUtil.isNotEmpty(model.getProject_pic())){
            model.getStrMap().put("picUrl", ServletUtil.getFileUrl(model.getProject_pic()));
        }
        request.setAttribute("commodit", model);
        List<PrjCategoryModel> categorys = prjCategoryService.getModelList(FrameUtil.newHashMap("is_used",1),DbWREnums.READ);
        request.setAttribute("categorys", categorys);
        return "commodit.edit";
    }

    /***
     * 商品详情
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id) throws Exception {
        if(null == id){
            FrameUtil.throwBaseException1("商品ID获取失败！");
        }
        MerchantProjectVerifyModel model = merchantProjectVerifyService.getModelById(id, DbWREnums.READ);
        if (model == null){
            FrameUtil.throwBaseException1("商品信息不存在！");
        }
        PrjCategoryModel categoryModel = prjCategoryService.getModelById(model.getCategory_id(), DbWREnums.READ);
        if (categoryModel == null){
            FrameUtil.throwBaseException1("该分类不存在！");
        }
        model.getStrMap().put("category", categoryModel.getName());

        if (StringUtil.isNotEmpty(model.getProject_pic())){
            model.getStrMap().put("picUrl", ServletUtil.getFileUrl(model.getProject_pic()));
        }
        request.setAttribute("commodit", model);
        List<PrjCategoryModel> categorys = prjCategoryService.getModelList(FrameUtil.newHashMap("is_used",1),DbWREnums.READ);
        request.setAttribute("categorys", categorys);
        return "commodit.detail";
    }

    /**
     * 提交修改
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/edit/submit")
    public void editSubmit(MerchantProjectVerifyModel model, MultipartHttpServletRequest request) throws Exception {
        if (model == null || model.getId() == null || model.getOrg_id() == null){
            FrameUtil.throwBaseException1("商品信息参数不完整！");
        }
        MerchantProjectVerifyModel mpv = merchantProjectVerifyService.getModelById(model.getId(),DbWREnums.READ);
        if (mpv == null || mpv.getOrg_id() != model.getOrg_id()){
            FrameUtil.throwBaseException1("商品信息不存在！");
        }
        if (mpv.getStatus() != 0){
            FrameUtil.throwBaseException1("该商品已审核，不能编辑！");
        }
        if (StringUtil.isEmpty(model.getProject_name())){
            FrameUtil.throwBaseException1("商品名称不能为空！");
        }
        if (model.getProject_name().length() > 15){
            FrameUtil.throwBaseException1("商品名称不能超过15个字！");
        }
        if (StringUtil.isEmpty(model.getCategory_id())){
            FrameUtil.throwBaseException1("请选择商品类目！");
        }
        if (StringUtil.isEmpty(model.getIntro())){
            FrameUtil.throwBaseException1("商品详情不能为空！");
        }
        if (model.getIntro().length() > 150){
            FrameUtil.throwBaseException1("商品详情不能超过150个字！");
        }
        if (StringUtil.isEmpty(model.getProject_price())){
            FrameUtil.throwBaseException1("商品价格不能为空！");
        }
        if (StringUtil.isEmpty(model.getTimes())){
            FrameUtil.throwBaseException1("请输入服务次数！");
        }
        if (!((model.getTimes() >= 1 && model.getTimes() <= 12))) {
            FrameUtil.throwBaseException1("服务次数必须介于1到12之间！");
        }
        if (StringUtil.isEmpty(model.getTime_limit())){
            FrameUtil.throwBaseException1("请输入服务时长！");
        }
        if (!((model.getTime_limit() >= 0 && model.getTime_limit() <= 12))){
            FrameUtil.throwBaseException1("服务时长必须介于0到12之间！");
        }
        List<MultipartFile> multipartFiles = request.getMultiFileMap().get("picData");
        //如果图片已重新选择
        if (multipartFiles != null && multipartFiles.size() > 0){
            if(multipartFiles.size()>1){
                FrameUtil.throwBaseException1("只允许上传一张图片！");
            }
            //先将新图片上传
            String image_path = FileUtil.uploadProjectApplyFileToRemote(multipartFiles.get(0), ReferenceTypeEnum.PROJECT_APPLY,mpv.getOrg_id());
            //删除掉老图片
            FileUtil.delteOssFile(mpv.getProject_pic());

            mpv.setProject_pic(image_path);
        }

        mpv.setProject_name(model.getProject_name());
        mpv.setCategory_id(model.getCategory_id());
        mpv.setIntro(model.getIntro());
        mpv.setProject_price(model.getProject_price());
        mpv.setTime_limit(model.getTime_limit());
        mpv.setTimes(model.getTimes());
        mpv.setUpdate_time(FrameUtil.getTime());

        if(merchantProjectVerifyService.update(mpv)!=1){
            FrameUtil.throwBaseException1("修改商品审核失败,请重试！");
        }

        this.successMsg(ServletUtil.getUrl("/commodit/list"), "修改成功!");
    }


    /**
     * 提交审核
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/check/submit")
    public void checkSubmit(MerchantProjectVerifyModel model) throws Exception {
        if (model == null || model.getId() == null || model.getOrg_id() == null){
            FrameUtil.throwBaseException1("商品信息参数不完整！");
        }
        MerchantProjectVerifyModel mpv = merchantProjectVerifyService.getModelById(model.getId(),DbWREnums.READ);
        if (mpv == null || mpv.getOrg_id() != model.getOrg_id()){
            FrameUtil.throwBaseException1("商品信息不存在！");
        }
        if (mpv.getStatus() != 0){
            FrameUtil.throwBaseException1("该商品处于非审核状态！");
        }

        //更新审核人信息
        AdminDataWrap adminDataWrap = AdminDataUtil.getAdminDataWrap(request,
                response);
        AdminModel adminModel = adminDataWrap.getAdminModel();

        Map<String, Object> param = FrameUtil.newHashMap("id", model.getId(),
                                                        "admin_id", adminModel.getAdmin_id(),
                                                        "status", model.getStatus(),
                                                        "verify_time", FrameUtil.getTime(),
                                                        "update_time",FrameUtil.getTime());
        merchantProjectVerifyService.updateAfterCheckout(param);
        this.successMsg(ServletUtil.getUrl("/commodit/list"), "审核成功!");
    }

    @Resource
    IMerchantProjectVerifyService merchantProjectVerifyService;

    @Resource
    IPrjCategoryService prjCategoryService;

}
